package com.apes.fn.serveControl.serverChildPackage;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.serveControl.serverParentPackage.PControlService;
import com.apes.fn.serveControl.serverParentPackage.ServeControl;
import com.apes.fn.server.servicePlan.repository.ServicePlanRepository;
import com.apes.fn.server.workDesk.repository.WorkDeskConfigRepository;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.fsm.FsmStateRepository;
import com.apes.framework.query.lib.PubToolUtil;
import com.apes.framework.query.SqlService;
import com.apes.framework.rop.session.SimpleSession;
import com.apes.framework.util.MapUtil;
import com.apes.framework.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.groupingBy;


/**
 * 关于总控-车辆总控
 * Creator: zouyc
 * CreateDate: 2021-01-29 10:09
 * Description:
 **/
@Service("controlService")
public class ControlService  extends PControlService {
    @Autowired
    ServeControl serveControl;
    @Autowired
    FsmStateRepository fsmStateRepository;
    @Autowired
    SqlService sqlService;
    @Autowired
    ServicePlanRepository servicePlanRepository;
    @Autowired
    WorkDeskConfigRepository workDeskConfigRepository;

    public Map obtainMainList(SimpleRequest re){
        JSONObject jo = re.getJO();
        JSONArray array = getObjects(re,"serverControl.obtainMainList",true); //对数据进行查询
        //分页数据封装在第一层
        JSONObject totalJson = null;
        if(array != null && array.size() != 0){
            totalJson = array.getJSONObject(0);
            array.remove(0);
        }

        List<Map> resultList = array.stream().map(item -> {
            JSONObject itemJson = (JSONObject) item;
            return MapUtil.mapper("current_point",itemJson.getString("CURRENT_POINT"),
                    "dept_name",itemJson.getString("DEPT_NAME"),
                    "brand_name",itemJson.getString("BRAND_NAME"),
                    "car_license",itemJson.getString("CAR_LICENSE"),
                    "current_state",itemJson.getString("CURRENT_STATE"),
                    "estimate_date", itemJson.getDate("ESTIMATE_DATE") == null ? null : DateUtil.format(itemJson.getDate("ESTIMATE_DATE"),DateUtil.SHOW_DATETIME_FORMAT),
                    "vip_level",itemJson.getString("VIP_LEVEL"),
                    "vip_liveness",itemJson.getString("VIP_LIVENESS"),
                    "dept_id",itemJson.getString("DEPT_ID"),
                    "pick_up_car",itemJson.getString("PICK_CAR_ID"),
                    "serve_type",itemJson.getString("SERVE_TYPE"),
                    "ve_id",itemJson.getString("VE_ID"),
                    "fn_customer_expand_id",itemJson.getString("FN_CUSTOMER_EXPAND_ID"),
                    "work_platform",distinctWorkPlat(itemJson.getString("WORK_PLATFORM"),","),
                    "pick_car_uname",itemJson.getString("PICK_CAR_UNAME"),
                    "consume_time_show", itemJson.getString("CONSUME_TIME_SHOW"),
                    "car_model_label", itemJson.getString("CAR_MODEL_LABEL"),
                    "beyong_flag",itemJson.getInteger("BEYONEFLAG"), //新版暂时还没处理这个子弹
                    "pick_car_time",itemJson.getDate("PICK_CAR_TIME") == null ? null : DateUtil.format(itemJson.getDate("PICK_CAR_TIME"),DateUtil.SHOW_DATETIME_FORMAT)
                    );
        }).collect(Collectors.toList());

        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(jo.getInteger("page"), jo.getInteger("size"), sort);
        PageImpl<Map> pPage = new PageImpl(resultList, pageable, totalJson == null ? 0 : totalJson.getJSONObject("SYS_PAGE").getInteger("Total"));  //总条数还没设置

        List list = getInStoreCarTypeCount(re);
        Map reMap = MapUtil.mapped(pPage);
        reMap.put("labelList",list);
        return reMap;
    }

    public List getInStoreCarTypeCount(SimpleRequest re) {
        JSONArray headOneArray = getObjectsForNull("serverControl.location");
        JSONArray headTwoArray = getObjectsForNull("serverControl.server");
        JSONArray headOneArrayR = getObjects(re,"serverControl.qryHeadOne",false);
        JSONArray headTwoArrayR = getObjects(re,"serverControl.qryHeadTwo",false);

        headOneArray.forEach(itemOne ->{
            JSONObject itemOneJson = (JSONObject)itemOne;
            List list = headOneArrayR.stream().filter(itemI ->{
                JSONObject itemIJson = (JSONObject)itemI;
                return itemIJson.getString("NAME").equals(itemOneJson.getString("NAME"));
            }).collect(Collectors.toList());
            if(list.size()> 0) itemOneJson.put("VALUE",((JSONObject)list.get(0)).getInteger("VALUE"));
        });
        headTwoArray.forEach(itemTwo ->{
            JSONObject itemTwoJson = (JSONObject)itemTwo;
            List list = headTwoArrayR.stream().filter(itemI ->{
                JSONObject itemIJson = (JSONObject)itemI;
                return itemIJson.getString("NAME").equals(itemTwoJson.getString("NAME"));
            }).collect(Collectors.toList());
            if(list.size()> 0) itemTwoJson.put("VALUE",((JSONObject)list.get(0)).getInteger("VALUE"));
        });

        headOneArray.addAll(headTwoArray);
        return headOneArray.stream().map(item->{
            JSONObject itemJson = (JSONObject)item;
            return MapUtil.mapper("id",itemJson.getString("ID"),"name",itemJson.getString("NAME"),"value",itemJson.getString("VALUE"),"key",itemJson.getString("KEY"));
        }).collect(Collectors.toList());
    }



    private JSONArray getObjects(SimpleRequest re,String address,boolean page) {
        JSONArray array;
        try {
            com.apestech.framework.json.JSONObject json= PubToolUtil.getInput(re);
            //多余参数移除
            removeExtraParam(json);
            SimpleSession session = (SimpleSession)re.getRopRequestContext().getSession();
            if(session!= null) json.put("postId",session.getPostId());

            if(page) {
                Optional.ofNullable(json.get("page")).orElseThrow(()->new RuntimeException("分页查询，请传入page参数"));
                Optional.ofNullable(json.get("size")).orElseThrow(()->new RuntimeException("分页查询，请传入page参数"));
                if(json.getInteger("size") > 2000) new RuntimeException("分页条数不能大于2000");
                json.put("page",json.getInteger("page") + 1);
            }else{
                if(json.get("page") != null) json.remove("page");
                if(json.get("size") != null) json.remove("size");
            }
            array = tranTypeArray(Optional.ofNullable(sqlService.queryId(address,json)).orElseGet(()->new com.apestech.framework.json.JSONArray()));
        }catch (Exception e){
            throw new RuntimeException(e);
        }
        return array;
    }

    private JSONArray getObjectsForNull(String address) {
        JSONArray array;
        try {
            array = tranTypeArray(Optional.ofNullable(sqlService.queryId(address,new com.apestech.framework.json.JSONObject())).orElseGet(()->new com.apestech.framework.json.JSONArray()));
        }catch (Exception e){
            throw new RuntimeException(e);
        }
        return array;
    }


    public void removeExtraParam(com.apestech.framework.json.JSONObject json){
        json.remove("customAction");
        json.remove("noSum");
        json.remove("queryid");
        json.remove("customQuery");
    }

    public Map obtainServeDetail(SimpleRequest re){
        JSONObject jo = re.getJO();
        JSONObject json = new JSONObject();
//        json.put("FN_CUSTOMER_EXPAND_ID",jo.getString("fn_customer_expand_id"));
//        json.put("DEPT_ID",jo.getString("dept_id"));
//        json.put("PICK_UP_CAR",jo.getString("pick_up_car"));
        json.put("VE_ID",jo.getJSONObject("node").getString("ve_id"));
        JSONObject car_info = (JSONObject) serveControl.obtainCarInfo(json).stream().findFirst().orElse(null);
        JSONObject pick_car_info = (JSONObject) serveControl.obtainPickCarInfo(json).stream().findFirst().orElse(null);
        if(car_info == null) throw new RuntimeException("扩展表信息不存在");
        if(pick_car_info == null) pick_car_info = new JSONObject();


        pick_car_info.putAll(MapUtil.mapper(
                "TIME",pick_car_info.get("FINISH_DATE")==null ? "--":pick_car_info.get("FINISH_DATE"),
                "U_NAME",pick_car_info.get("F_UID")==null ? "--":pick_car_info.get("F_UID"),
                "ADVANCE_REMARK",pick_car_info.get("ADVANCE_REMARK")==null ? "--": pick_car_info.get("ADVANCE_REMARK"),
                "ESTIMATE_DATE",pick_car_info.get("ESTIMATE_DATE")==null ? "--": pick_car_info.get("ESTIMATE_DATE"),
                "FAULT_DESCRIPTION",pick_car_info.get("FAULT_DESCRIPTION")==null ? "--": pick_car_info.get("FAULT_DESCRIPTION")
                ));


        List wait_confirm = new ArrayList();
        List wait_work = new ArrayList();
//        List wait_test = new ArrayList();
//        List wait_money = new ArrayList();
        List wait_prduct = new ArrayList();
        List wait_need = new ArrayList();
        JSONArray detailList = serveControl.obtainDetailList(json);

        //方案分组
        Map plan_group = detailList.stream().collect(groupingBy((item)->{
            JSONObject itemJson = (JSONObject)item;
            return  itemJson.getString("PLAN_ID");
        }));

        plan_group.forEach((k,v)->{
            //方案确认前块的数据
            List<JSONObject> J = (List<JSONObject>) v;
            JSONArray list = JSONArray.parseArray(v.toString());
            JSONObject vJson1 = new JSONObject();
            vJson1.put("plan_id",list.getJSONObject(0).getString("PLAN_ID"));
            vJson1.put("plan_state",list.getJSONObject(0).getString("PLAN_STATE_NAME"));
            vJson1.put("confirm_date",J.get(0).getString("CONFIRM_DATE")==null?"--":J.get(0).getString("CONFIRM_DATE"));
            vJson1.put("plan_create_date",J.get(0).getString("CREATE_DATE"));
            vJson1.put("plan_receivable_date",J.get(0).getString("RECEIVABLE_DATE")==null?"--":J.get(0).getString("RECEIVABLE_DATE"));
            vJson1.put("clerk_id",list.getJSONObject(0).getString("CLERK_ID")==null?"--":list.getJSONObject(0).getString("CLERK_ID"));
//            vJson1.put("plan_point",list.getJSONObject(0).getString("POINT_NAME"));
//            vJson1.put("es_date",list.getJSONObject(0).getDate("ES_DATE"));
/*            vJson1.put("detailList",list.stream().map(vItem ->{
                JSONObject iItem = (JSONObject)vItem;
                return MapUtil.mapper("product_name",iItem.getString("PRODUCT_NAME"),"qty_sale",iItem.getInteger("QTY_SALE"));
            }).collect(Collectors.toCollection(ArrayList::new))
            );*/
            wait_confirm.add(vJson1);


/*            if("qualityTest".equals(list.getJSONObject(0).getString("PLAN_STATE"))|| "receivables".equals(list.getJSONObject(0).getString("PLAN_STATE"))){
                //质检后数据
                JSONObject vJson2 = new JSONObject();
                vJson2.put("plan_id",list.getJSONObject(0).getString("PLAN_ID"));
                vJson2.put("plan_amount",list.getJSONObject(0).getDoubleValue("SALES_AMOUNT"));
                vJson2.put("plan_state","qualityTest".equals(list.getJSONObject(0).getString("PLAN_STATE")) ? "待结算":"已结算");
                vJson2.put("re_date",list.getJSONObject(0).getDate("RECEIVABLE_DATE"));
                vJson2.put("re_uname",list.getJSONObject(0).getString("RECEIVABLE_UNAME"));
                vJson2.put("detailList",list.stream().map(vItem ->{
                            JSONObject iItem = (JSONObject)vItem;
                            return MapUtil.mapper("product_name",iItem.getString("PRODUCT_NAME"),"qty_sale",iItem.getInteger("QTY_SALE"));
                        }).collect(Collectors.toCollection(ArrayList::new))
                );
                wait_money.add(vJson2);
            }*/

        });
        wait_work = detailList.stream().filter(item ->{
            JSONObject mItemJson = (JSONObject)item;
            return "20".equals(mItemJson.getString("PRODUCT_GROUP")) || "ServicePlanItem.assistType.outer".equals(mItemJson.getString("PLAN_ASSIST_TYPE"));
        }).map(item->{
            JSONObject mItemJson = (JSONObject)item;
            return MapUtil.mapper(
                    "plan_id",mItemJson.getString("PLAN_ID"),
                    "product_name",mItemJson.getString("PRODUCT_NAME"),
                    "qty_sale",mItemJson.getInteger("QTY_SALE"),
                    "service_side_name",mItemJson.getString("SERVE_SIDE_NAME"),
//                    "mten_state",mItemJson.getString("TEN_STATE"),
                    "mian_state",transWorkState(mItemJson.getString("DISPATCHE_STATE"),mItemJson.getString("MIAN_STATE"),mItemJson.getString("MAIN_WORK_STATE")),
                    "main_rank_date",mItemJson.getString("MAIN_RANK_DATE"),
//                    "mten_work_state",mItemJson.getString("TEN_WORK_STATE"),
                    "work_time","0分钟".equals(mItemJson.getString("WORK_TIME"))&&mItemJson.getString("WORK_FINISH_DATE")==null ? "--": mItemJson.getString("WORK_TIME"),
                    "work_finish_date",mItemJson.getString("WORK_FINISH_DATE"),
                    "mten_worker",mItemJson.getString("TEN_WORKER") == null ? "--": mItemJson.getString("TEN_WORKER"),
                    "test_state",mItemJson.getString("QUALITY_TEST_DATE") == null ? "--"
                            : "0".equals(mItemJson.getString("QUALITY_FLAG")) ? "不通过" : "通过",
                    "test_date",mItemJson.getString("QUALITY_TEST_DATE") == null ? "--": mItemJson.getString("QUALITY_TEST_DATE") ,
                    "test_uname",mItemJson.getString("QUALITY_TEST_UNAME") == null ? "--": mItemJson.getString("QUALITY_TEST_UNAME")
            );
        }).collect(Collectors.toList());

        //质检数据
/*
        wait_test = detailList.stream().filter(item ->{
            JSONObject mItemJson = (JSONObject)item;
            return mItemJson.get("PLAN_FINISH_DATE") != null ||  "1".equals(mItemJson.getString("PLAN_FINISH_WORK"));
        }).map(item->{
            JSONObject mItemJson = (JSONObject)item;
            return MapUtil.mapper(
//                    "plan_id",mItemJson.getString("PLAN_ID"),
                    "product_name",mItemJson.getString("PRODUCT_NAME"),
                    "qty_sale",mItemJson.getInteger("QTY_SALE"),
                    "test_state",mItemJson.getString("QUALITY_TEST_DATE") == null ? "待质检"
                            : "0".equals(mItemJson.getString("QUALITY_FLAG")) ? "不通过" : "通过",
                    "test_date",mItemJson.getString("QUALITY_TEST_DATE"),
                    "test_uname",mItemJson.getString("QUALITY_TEST_UNAME")
            );
        }).collect(Collectors.toList());
*/
        //配件领用
        wait_prduct = detailList.stream().filter(item ->{
            JSONObject mItemJson = (JSONObject)item;
            return "10".equals(mItemJson.getString("PRODUCT_GROUP"));
        }).map(item->{
            JSONObject mItemJson = (JSONObject)item;
            return MapUtil.mapper(
                    "plan_id",mItemJson.getString("PLAN_ID"),
                    "product_name",mItemJson.getString("PRODUCT_NAME"),
                    "uom_name",mItemJson.getString("UOM_NAME"),
                    "usable_qty",mItemJson.getInteger("USABLE_QTY") ,
                    "qty_receive",mItemJson.getInteger("QTY_RECEIVE"),
                    "location_name",mItemJson.getString("LOCATION_NAME")
            );
        }).collect(Collectors.toList());

        //要货明细
        wait_need = detailList.stream().filter(item ->{
            JSONObject mItemJson = (JSONObject)item;
            return "10".equals(mItemJson.getString("PRODUCT_GROUP")) && mItemJson.getString("REQUIRE_ID")!=null ;
        }).map(item->{
            JSONObject mItemJson = (JSONObject)item;
            return MapUtil.mapper(
                    "plan_id",mItemJson.getString("PLAN_ID"),
                    "product_name",mItemJson.getString("PRODUCT_NAME"),
                    "uom_name",mItemJson.getString("UOM_NAME"),
                    "qty_require",mItemJson.getInteger("QTY_REQUIRE"),
                    "qty_assigned",mItemJson.getInteger("QTY_ASSIGNED"),
                    "qty_end",mItemJson.getInteger("QTY_END"),
                    "qty_arrive",mItemJson.getInteger("QTY_ARRIVE"),
                    "plant_name",mItemJson.getString("PLANT_NAME")
            );
        }).collect(Collectors.toList());

        return MapUtil.mapper("car_info",car_info,"pick_car_info",pick_car_info,"wait_confirm",wait_confirm,"wait_work",wait_work,"wait_prduct",wait_prduct,"wait_need",wait_need);
    }

    /**
     * 转换工单状态
     * @param dispatcheState
     * @param mianState
     * @param mainWorkState
     * @return
     */
    public String transWorkState(String dispatcheState,String mianState,String mainWorkState){
        if (dispatcheState==null)dispatcheState="";
        if (mianState==null)mianState="";
        if (mainWorkState==null)mainWorkState="";
        switch (mianState){
            case"create":
                switch (mainWorkState){
                    case "wait":
                        if ("none".equals(dispatcheState))return "待施工";
                        break;
                    case "working":
                        return "施工中";
                    case "pause":
                        return "暂停施工";
                        default:
                            return "--";
                }
                break;
            case "outer":
                if ( "waitDispatch".equals(dispatcheState)){
                    return "外协待派工";
                }
                if ( "wait".equals(mainWorkState) && "dispatch".equals(dispatcheState)){
                    return "外协待施工";
                }
                break;
            case "inner":
                return "内协中";
            case "finish":
                return "完工";
            case "termination":
                return "终止";
                default:
                    if ("wait".equals(mainWorkState)&&"back".equals(dispatcheState))return "外协退回";
                    break;
        }
        return "--";
    }

    public String distinctWorkPlat(String str,String patten){
        if(str == null) str =  "";
        String[] strs = str.split(patten);
        HashSet set =new HashSet<>();
        Arrays.stream(strs).forEach(itemDistinct ->{
            set.add(this.obtainWorkPlatForm(itemDistinct));
        });
        return (String) set.stream().collect(Collectors.joining(",","",""));
    }

    /**
     * 工单工作平台转化
     * @param str
     * @return
     */
    public String obtainWorkPlatForm(String str){
        String re = "其他";
        if("cosmetology".equals(str)){
            re = "美容";
        }else if("machineRepa".equals(str)){
            re = "机修";
        }else if("sprayPaint".equals(str)){
            re = "钣喷";
        }
        return re;
    }



    //外协总控驱动--------------------------------

    /**
     *  leftText: '待提交方案',
     *           rightText: '今天/昨天（100/200）
     * @param req
     * @return
     */
    public List<Map> obtainOutAssist(SimpleRequest req){
        JSONArray array = serveControl.obtainOutAssist();
        return new ArrayList(array.stream().map(item->{
            JSONObject json = (JSONObject)item;
            return MapUtil.mapper("LEFTTEXT","待收款结算","RIGHTTEXT",json.getString("AMOUNT"));
        }).collect(Collectors.toList()));
    }
    //外协总控驱动--------------------------------
    public Page<Object>  obtainOutAssistList(SimpleRequest re){
        JSONArray resultList = serveControl.obtainOutAssistList(re.getJO());
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(((Integer) re.get("page")) - 1, re.get("size"), sort);
        PageImpl<Object> pPage = new PageImpl(resultList, pageable, resultList.size() == 0 ? 0 : resultList.getJSONObject(0).getIntValue("TOTAL"));
        return pPage;
    }
}
